package com.tezign.intelligence.mini.dam.aifamilyconsultant.util;

import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.github.cdimascio.dotenv.Dotenv;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant.*;

@Component
@Slf4j
@RequiredArgsConstructor
public class SmartVoiceUtil {

	// 地域ID
	private static final String REGIONID = "cn-shanghai";
	// 获取Token服务域名
	private static final String DOMAIN = "nls-meta.cn-shanghai.aliyuncs.com";
	// API版本
	private static final String API_VERSION = "2019-02-28";
	// API名称
	private static final String REQUEST_ACTION = "CreateToken";

	// 响应参数
	private static final String KEY_TOKEN = "Token";
	private static final String KEY_ID = "Id";
	private static final String KEY_EXPIRETIME = "ExpireTime";

	private final RedisTemplate<String, String> redisTemplate;

	private static final String TOKEN_KEY = "token_key";


	public String getToken() throws ClientException {
		String value = redisTemplate.opsForValue().get(TOKEN_KEY);
		if (StringUtils.isNotBlank(value)) {
			return value;
		}

		Dotenv dotenv = Dotenv.load();
		String accessKeyId = dotenv.get(ALIYUN_AK_ID);
		String accessKeySecret = dotenv.get(ALIYUN_AK_SECRET);

		// 创建DefaultAcsClient实例并初始化
		DefaultProfile profile = DefaultProfile.getProfile(
				REGIONID,
				accessKeyId,
				accessKeySecret);

		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setDomain(DOMAIN);
		request.setVersion(API_VERSION);
		request.setAction(REQUEST_ACTION);
		request.setMethod(MethodType.POST);
		request.setProtocol(ProtocolType.HTTPS);

		CommonResponse response = client.getCommonResponse(request);
		log.info("response={}", response.getData());
		if (response.getHttpStatus() == 200) {
			JSONObject result = JSON.parseObject(response.getData());
			String token = result.getJSONObject(KEY_TOKEN).getString(KEY_ID);
			long expireTime = result.getJSONObject(KEY_TOKEN).getLongValue(KEY_EXPIRETIME);
			log.info("Token={}", token);
			log.info("Token过期时间={}", expireTime);
			// 将10位数的时间戳转换为北京时间
			String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(expireTime * 1000));
			log.info("Token有效期的北京时间：{}", expireDate);
			redisTemplate.opsForValue().set(TOKEN_KEY, token, expireTime - System.currentTimeMillis() / 1000, TimeUnit.SECONDS);
			return token;
		} else {
			log.info("获取Token失败！");
		}
		return null;
	}
}